import md5 from "crypto-js/md5";

export default function sign(obj) {
    const timp = new Date().getTime();
    const nonce = generateRandomString(32);
    const sign = genSignParams(obj, timp, nonce);
    return {
        "X-Nonce": nonce,
        "X-Timestamp": timp,
        "X-Sign": sign,
    };
}

function generateRandomString(length) {
    const charset =
        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    let result = "";
    for (let i = 0; i < length; i++) {
        const randomChar = charset[Math.floor(Math.random() * charset.length)];
        result += randomChar;
    }
    return result;
}

function genSignParams(obj, timp, nonce) {
    const inObject = Object.assign({}, obj);
    const sorter = function (inObject) {
        const sortedJson = {};
        const sortedKeys = Object.keys(inObject).sort();
        for (var i = 0; i < sortedKeys.length; i++) {
            sortedJson[sortedKeys[i]] = inObject[sortedKeys[i]];
        }
        return sortedJson;
    };
    const sortedParam = sorter(inObject);

    let needSignatureStr = convertObjectToQueryString(sortedParam);
    const secretKey = "WQBymFuoi5okgiODmLSCbSIvT2PQla8ctWJxkDH7PEqBmfZmnTu8zeFRS4jAo7";
    if (needSignatureStr) {
        needSignatureStr += `&timestamp=${timp}&nonce=${nonce}&secret=${secretKey}`;
        return md5(needSignatureStr).toString().toUpperCase();
    } else {
        needSignatureStr = `timestamp=${timp}&nonce=${nonce}&secret=${secretKey}`
        return md5(needSignatureStr).toString().toUpperCase();
    }
}

function convertObjectToQueryString(obj) {
    const queryStringParts = [];

    for (const key in obj) {
        if (obj.hasOwnProperty(key)) {
            let value = obj[key];

            // 只处理非空字符串、非空数组、非以 'https://' 开头的字符串
            if (typeof value === "string") {
                if (value.length > 0 && !value.startsWith("https://")) {
                    queryStringParts.push(
                        `${(key)}=${(value)}`
                    );
                }
            } else if (Array.isArray(value) && value.length > 0) {
                value.forEach((val) => {
                    if (typeof val === "string" && !val.startsWith("https://")) {
                        queryStringParts.push(
                            `${(key)}=${(val)}`
                        );
                    }
                });
            } else if (typeof value === "number") {
                // 对于数字字段，直接添加
                queryStringParts.push(
                    `${(key)}=${(value)}`
                );
            }
        }
    }

    return queryStringParts.join("&");
}